package com.yy.loramodule.bp;

import android.util.Log;

import com.run.serial.SerialPort;

import java.io.File;

public class BpUartUtils {
    private static final String TAG = "BpUartUtils";
    private static BpUartUtils bpUtils = null;

    private SerialPort serialPort = null;

    private boolean openSuccess = false;

    private BpUartUtils() {
    }

    public static BpUartUtils getInstance() {
        if (bpUtils == null) {
            synchronized (BpUartUtils.class) {
                if (bpUtils == null) {
                    bpUtils = new BpUartUtils();
                }
            }
        }
        return bpUtils;
    }

    /**
     * 该方法建议值Application执行
     *
     //* @param context 上下文
     * @param baud    设置波特率,9600的倍数,例如:38400
     * @param strPort 设置串口路径,例如:/dev/ttSy5
     * @return 是否正确打开串口
     */
    public synchronized boolean init(int baud, String strPort) {//@NonNull Context context,
        if (openSuccess) {
            throw new RuntimeException("serial is open succeed");
        }
        int baudRate;
        if (baud <= 0) {
            throw new IllegalArgumentException("the baud is wrongful,baud must be baud > 0");
        }
        if ((baud % 50) != 0) {
//            throw new IllegalArgumentException("the baud is wrongful,baud must be baud % 9600 == 0");
        }
        baudRate = baud;

        String port;
        if (strPort.equals("")) {
            throw new IllegalArgumentException("the strPort is wrongful,strPort not around \"\"");
        }
        port = strPort;

        try {
            //打开串口通信
            openSuccess = false;
            serialPort = new SerialPort(new File(port), baudRate, 0);
            openSuccess = true;
            Log.d(getClass().getSimpleName(), "===========openSuccess====================");
        } catch (Exception e) {
            e.printStackTrace();
            openSuccess = false;
        }
        return openSuccess;
    }

    public boolean stopSerial() {
        openSuccess = false;
        try {
            if (serialPort != null) {
                serialPort.close();
            }
        } catch (Exception ignore) {
            return false;
        }
        return true;
    }

    public boolean isOpenSuccess() {
        return openSuccess;
    }
}